package com.franklin.maven.localcleaner.action;

import com.franklin.maven.localcleaner.utils.DialogUtils;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.project.actions.ReimportAction;
import org.jetbrains.idea.maven.utils.MavenUtil;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * Idea maven插件刷新项目（Reload All Maven Projects）
 * see also: {@link ReimportAction}
 * @author Franklin
 * @since 2022/04/04 20:27
 */
public class ActionUtils {

    /**
     * 刷新Maven项目
     * @param project
     * @param e
     * @return
     */
    public static boolean refreshMavenProjects(@NotNull Project project, @Nullable AnActionEvent e){
        final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
        if (Objects.nonNull(projectsManager)) {
            if (MavenUtil.isProjectTrustedEnoughToImport(projectsManager.getProject())) {
                FileDocumentManager.getInstance().saveAllDocuments();
                projectsManager.forceUpdateAllProjectsOrFindAllAvailablePomFiles();
                return true;
            }
        }
        return false;
    }

    /**
     * 打开目录
     * @param filePath
     */
    public static void openFileInExplorer(String filePath){
        File file = new File(filePath);
        try {
            Desktop.getDesktop().open(file);
        } catch (IOException e) {
            e.printStackTrace();
            DialogUtils.showConfirmDialog("IO Exception","打开目录出现异常");
        }
    }
}
